package com.falko.android.raven.renderer;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11Ext;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.falko.android.raven.util.AndroidUtil;

public class BackgroundImage {

	public String path_;
	public Texture texture_;
	public float scaleX_;
	public float scaleY_;
	public float width_;
	public float height_;

	public BackgroundImage() {
		texture_ = new Texture();
		path_ = null;
	}

	public void draw(GL10 gl) {

		if (!texture_.loaded) {
			return;
		}

		gl.glBindTexture(GL10.GL_TEXTURE_2D, texture_.name);
		((GL11Ext) gl).glDrawTexfOES(0, 0, 0, width_, height_);

	}

	public void invalidate() {
		texture_.loaded = false;
	}

	public void load(GL10 gl) {

		if (texture_.loaded != false || path_ == null) {
			return;
		}

		Bitmap sourceBitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		int sampleSize = 1;
		while (sourceBitmap == null) {
			options.inSampleSize = sampleSize;
			try {
				sourceBitmap = BitmapFactory.decodeFile(path_, options);

			} catch (OutOfMemoryError e) {
				sourceBitmap = null;
				sampleSize++;
			} catch (Exception e) {
				return;
			}
		}
		Bitmap cropedBitmap = null;
		Bitmap bitmapGL = null;

		int x = Math.round(scaleX_ * sourceBitmap.getWidth());
		int y = Math.round(scaleY_ * sourceBitmap.getHeight());
		int width = Math.round(width_ * scaleX_);
		width = x + width > sourceBitmap.getWidth() ? sourceBitmap.getWidth()
				- x : width;
		int height = Math.round(height_ * scaleY_);
		height = y + height > sourceBitmap.getHeight() ? sourceBitmap
				.getHeight() - y : height;

		cropedBitmap = Bitmap.createBitmap(sourceBitmap, x, y, width, height);

		width = (int) upperPowerOfTwo(cropedBitmap.getWidth());
		height = (int) upperPowerOfTwo(cropedBitmap.getHeight());

		bitmapGL = Bitmap
				.createScaledBitmap(cropedBitmap, width, height, false);

		AndroidUtil.loadTexture(gl, bitmapGL, texture_);

		try {
			sourceBitmap.recycle();
			cropedBitmap.recycle();
			bitmapGL.recycle();
		} catch (Exception e) {
			// ignore
		}

	}

	// I did not come up with this crazy stuff
	// Credit: http://graphics.stanford.edu/~seander/bithacks.html
	private long upperPowerOfTwo(long v) {
		if ((v != 0) && ((v & (v - 1)) == 0)) {
			return v;
		}

		v--;
		v |= v >>> 1;
		v |= v >>> 2;
		v |= v >>> 4;
		v |= v >>> 8;
		v |= v >>> 16;
		v++;

		return v;
	}
}
